﻿

#include <cmath>
#include <QDebug>
#include <QFontMetrics>
#include <QGuiApplication>
#include "element.h"
#include "semiautoplinesfinder.h"
#include "DisplayWidget.h"
#include "./qtOpencv/convert.h"
#include "opencv2/highgui.hpp"

namespace Qly
{
void DrawParallelLineAuto::draw( QPainter &painter )
{
    if( m_state != DS_IDLE )
    {
        painter.save();
        //painter.setFont(m_textFont);
        painter.setPen(m_linePen);
        painter.drawLine ( m_points[0], m_points[1] );
        painter.drawLine ( m_line2_start, m_line2_end );
        painter.drawLine ( m_line1_start, m_line1_end );
        if(m_state != Element::DS_FINISH)
        {
            painter.drawLine ( m_line1_end, m_line2_end );
            painter.drawLine ( m_line1_start, m_line2_start );
        }
        else
        {
            m_textBlock.draw(painter);
        }
        painter.restore();
    }
}

cv::Point2i QPointF2cvPoint2i(QPointF p)
{
    cv::Point2i d;
    d.x = p.x();
    d.y = p.y();

    return d;
}

QPointF cvPoint2d2QPointF(cv::Point2d d)
{
    QPointF p;
    p.setX(d.x);
    p.setY(d.y);
    return p;
}

int DrawParallelLineAuto::mouseLButtonRelease(QPointF point)
{
    if( m_state == DS_STATE1 )
    {
        m_points[1] = point;

        /// 计算真正的平行线
        if( m_points[0] == m_points[1] )
        {
            m_state = Element::DS_ERROR;
            return 0;
        }

        QImage image = m_disp->getImage(false);
        cv::Mat mat = QImage2cvMat(image, false);
        cv::Mat gray, edge;
        cv::cvtColor(mat, gray, cv::COLOR_RGBA2GRAY);
        cv::Canny(gray, edge, 50, 150);
//        cv::dilate(edge, edge, cv::Mat());
        cv::dilate(edge, edge, cv::Mat());
//        cv::erode(edge, edge, cv::Mat());
        cv::erode(edge, edge, cv::Mat());
//        cv::namedWindow("edge", cv::WINDOW_GUI_NORMAL);
//        cv::imshow("edge", edge);

        cv::Point2i start = QPointF2cvPoint2i(m_points[0]);
        cv::Point2i end = QPointF2cvPoint2i(m_points[1]);

        cv::Point2d p1, p2;
        semiautoPlinesFinder(mat, edge, start, end, p1, p2, 15 );

//        cv::line(mat, start, end, cv::Scalar(255,255,255), 1);
//        cv::namedWindow("test", cv::WINDOW_NORMAL);
//        cv::imshow("test", mat);

        QPointF d1, d2;
        d1 = cvPoint2d2QPointF(p1);
        d2 = cvPoint2d2QPointF(p2);
        m_points[0] = d1;
        m_points[1] = d2;
        if(m_points[0] == m_points[1])
        {
            m_state = DS_ERROR;

            return 1;
        }
        build(d1, d2);
        return 1;
    }
    return 0;
}
}//namespace Qly
